#!/bin/bash
##############################################################
## @Description Set software user, group and privilege
## @Usage privilege.sh src_path log_path cfg_path
## @Options src_path  log_path cfg_path
## @Version V100R020C00RC1
## @Created 2020/08/06
##############################################################

# import log and common function
SCRIPT_PATH="$(dirname $(readlink -f $0))"
. ${SCRIPT_PATH}/log_util.sh

declare -i err_parameter_num_fail=1
HW_USER="HwHiAiUser"
HW_GROUP="HwHiAiUser"
HW_HOME=/home/HwHiAiUser
# AtlasEdge source work path,eg /opt/middleware/AtlasEdge
SRC_PATH=""
# AtlasEdge log path, eg /var/alog/AtlasEdge_log/
LOG_PATH=""
# Log rotate path
LOG_ROTATE_PATH=/home/log/alog/AtlasEdge_log
EDGE_WORK_DIR="/opt/middleware"

#755
IEF_DIR=("/opt/IEF" \
    "/opt/FD/Edge-core")

# 700
ATLAS_HOME_DIR_R=("/home/log/alog" \
    "/opt/edge-installer" \
    "/opt/edge-register" \
    "/opt/Atlastmp" \
    "/opt/FD/Edge-core/bin/conf")

HOME_DATA_CFG_FILE=("/opt/edge-register/conf/" \
    "/opt/FD/Edge-core/bin/conf/" \
    "/opt/edge-installer/conf/" \
    "/home/data/config/main/config_default/" \
    "/home/data/config/main/config/work/" \
    "/home/data/config/main/config/factor/" \
    "/home/data/config/bak/config/work/" \
    "/home/data/config/bak/config/factor/")

# config file 644
ATLAS_EDGE_CFG_FILE_SUFFIX=("*.ini" \
    "*.xml" \
    "*.html" \
    "*.json" \
    "*.yaml" \
    "*.css" \
    "*.crt" \
    "\.*\.enc" \
    "*.cfg" \
    "*.log" \
    "*.txt" \
    "*.pem" \
    "*.png" \
    "*.bak" \
    "*.db" \
    "*.checksum")

# config file 644
ATLAS_EDGE_SPECIAL_CFG_FILE_SUFFIX=("asset_tag" \
    "version" \
    "NODE_INFO" \
    "NODE_ID" \
    "FONT_LICENSE" \
    ".factor.info" \
    "atlasedge.service" \
    "mod_file_list.txt" \
    "pause-atlas.tar.gz")

ATLAS_EDGE_CERT_FILE_SUFFIX=("*.pem" \
    "*.crt" \
    "FD_Backup.checksum" \
    "FD_Work.checksum")

# config file 600
ATLAS_EDGE_CFG_FILE_OTHER=("/opt/edge-installer/conf/*.yaml" \
    "/opt/edge-installer/conf/*.json" \
    "/opt/edge-installer/version" \
    "/opt/edge-register/version" \
    "/opt/FD/Edge-core/*.db")


# program file 500
ATLAS_EDGE_PROC_DIR_FILE_OTHER=("/opt/edge-installer/encrypt_tool" \
    "/opt/edge-installer/installer" \
    "/opt/edge-installer/conf/script" \
    "/opt/edge-installer/conf/script/*.sh" \
    "/opt/edge-register/encrypt_tool" \
    "/opt/edge-register/register")

# program file 500
ATLAS_EDGE_PROC_FILE_SUFFIX=("*.sh" \
    "*.py" \
    "*.pyc" \
    "*.sh" \
    "*.js" \
    "websocket_FD.so" \
    "*.h" \
    "*.sh.back" \
    "*.tcc")

ATLAS_EDGE_PROC_SPECIAL_FILE_SUFFIX=("encrypt_tool" \
    "installer" \
    "edge_core" \
    "register" \
    "encrypt_code" \
    "update_workkey" \
    "verify_tool" \
    "AscendK8sDevicePlugin")

ATLAS_OTHER_SCRIPT_FILE=("edge_main.sh" \
    "mod_backup.sh" \
    "common.sh" \
    "start.sh" \
    "stop.sh" \
    "mdw_log_retate_by_size.sh" \
    "log_util.sh" \
    "ha_status_monitor.sh" \
    "config_hahandler.sh" \
    "ip_conflict_check.sh")

# 400
ATLAS_LOG_BAK_FILE=("/home/log/alog/AtlasEdge_log/*")

function config_file_home_privilege() {
    chown root:root -R ${SRC_PATH}
    chown root:root /home/data
    chown root:root -R /home/data/config
    chmod 755 /home/data
    chmod 755 -R /home/data/config
    chmod 755 -R ${SRC_PATH}
    chmod 775 ${LOG_PATH}
    chown root:root /var/alog
    chown root:HwHiAiUser ${LOG_PATH}
    for path in "${ATLAS_HOME_DIR_R[@]}"; do
        if [ -d "${path}" ]; then
            chmod 700 -R $path
        fi
    done

    local lms_log_path=$(dirname ${LOG_PATH})/lms/
    chown HwHiAiUser:HwHiAiUser ${lms_log_path}
    chmod 700 ${lms_log_path}
}

function config_dir_file_privilege() {
    for path in "${ATLAS_LOG_BAK_FILE[@]}"; do
        chmod 400 $path
    done

    chmod -R 500 ${SRC_PATH}/edge_backup/software/edge_site/opensource/*
    chmod -R 500 ${SRC_PATH}/software/edge_site/opensource/*

    for path in "${ATLAS_EDGE_CFG_FILE_OTHER[@]}"; do
        chmod 600 $path > /dev/null 2>&1
    done

    find ${LOG_PATH} -type f | xargs -n1 chmod 600

    for path in "${HOME_DATA_CFG_FILE[@]}"; do
        find $path -type f | xargs -n1 chmod 600 > /dev/null 2>&1
    done

    for path in "${ATLAS_EDGE_PROC_DIR_FILE_OTHER[@]}"; do
        chmod 500 $path > /dev/null 2>&1
    done

    for path in "${IEF_DIR[@]}"; do
        if [ -d "${path}" ]; then
            chmod 755 $path > /dev/null 2>&1
        fi
    done
}

function set_proc_file_privilege() {
    find ${SRC_PATH} -type f -name "*.so" | xargs -n1 chmod 755 > /dev/null 2>&1
    for suffix in "${ATLAS_EDGE_PROC_FILE_SUFFIX[@]}"; do
        find ${SRC_PATH} -type f -name "${suffix}" | xargs -n1 chmod 500 > /dev/null 2>&1
    done

    for suffix in "${ATLAS_EDGE_PROC_SPECIAL_FILE_SUFFIX[@]}"; do
        find ${SRC_PATH} -type f -name "${suffix}" | xargs -n1 chmod 500 > /dev/null 2>&1
    done
}

function set_cfg_file_privilege() {
    for suffix in "${ATLAS_EDGE_CFG_FILE_SUFFIX[@]}"; do
        find ${SRC_PATH} -type f -name "${suffix}" | xargs -n1 chmod 644 > /dev/null 2>&1
    done

    for suffix in "${ATLAS_EDGE_SPECIAL_CFG_FILE_SUFFIX[@]}"; do
        find ${SRC_PATH} -type f -name "${suffix}" | xargs -n1 chmod 644 > /dev/null 2>&1
    done

    for suffix in "${ATLAS_EDGE_CERT_FILE_SUFFIX[@]}"; do
        find ${SRC_PATH} -type f -name "${suffix}" | xargs -n1 chmod 600 > /dev/null 2>&1
    done
}

function set_special_file_privilege() {
    chmod 400 ${SRC_PATH}/software/edge_portal/alarm.xml/*.xml
    chmod 400 ${SRC_PATH}/software/edge_portal/help/en/*.html ${SRC_PATH}/software/edge_portal/help/zh/*.html
    find ${WORK_DIR} -name "*.log" | xargs -n1 chmod 600 > /dev/null 2>&1
    if [ -e /etc/redhat-release ] && [ ! -e /etc/lsb-release ]; then
        chmod 600 /etc/pki/ca-trust/source/anchors/FD.crt
    else
        chmod 600 /usr/local/share/ca-certificates/FD.crt
    fi
}

function set_edge_portal_privilage() {
    if [ -d "${WORK_DIR}/edge_portal" ];then
        chmod 700 -R ${WORK_DIR}/edge_portal
        find ${WORK_DIR}/edge_portal -type d -name "controllers" | xargs -n1 chmod 500
        find ${WORK_DIR}/edge_portal -type d -name "creatInstance" | xargs -n1 chmod 500
        find ${WORK_DIR}/edge_portal -name "*.html" | xargs -n1 chmod 600
        find ${WORK_DIR}/edge_portal -name "*.js" | xargs -n1 chmod 500
    fi
}

function set_other_privilage() {
    for file_name in "${ATLAS_OTHER_SCRIPT_FILE[@]}"; do
        find ${SRC_PATH} -type f -name "${file_name}" | xargs -n1 chmod 755 > /dev/null 2>&1
    done
}

function config_atlas_edge_privilege() {
    config_file_home_privilege
    config_dir_file_privilege
    set_proc_file_privilege
    set_cfg_file_privilege
    set_special_file_privilege
    set_edge_portal_privilage
    set_other_privilage
}

function set_path_hw_usr_group() {
    if [[ ${#} -ne 1 || -z "$1" || ! -d $1 ]]; then
        return
    fi
    local visit_path=$1
    chown $HW_USER:$HW_GROUP $visit_path -R
}

function set_path_hw_permission() {
    if [[ ${#} -lt 2 || -z "$1" || ! -d $1 ]]; then
        return
    fi
    chmod $2 -R $1
}

function set_path_hw_usr_permission() {
    if [ ${#} -eq 2 ]; then
        local file_dir=$1
        local file_permission=$2
        set_file_hw_usr_group $file_dir
        set_file_hw_permission $file_dir $file_permission
    fi
}

function set_file_hw_usr_group() {
    if [[ ${#} -ne 1 || -z "$1" || ! -e $1 ]]; then
        return
    fi
    local visit_file=$1
    chown $HW_USER:$HW_GROUP $visit_file
}

function set_file_hw_permission() {
    if [[ ${#} -lt 2 || -z "$1" || ! -e $1 ]]; then
        return
    fi
    chmod $2 $1
}

function set_file_hw_usr_permission() {
    if [ ${#} -eq 2 ]; then
        local file_path=$1
        local file_permission=$2
        set_file_hw_usr_group $file_path
        set_file_hw_permission $file_path $file_permission
    fi
}

function config_html_user_group() {
    grep -q brd_t=sei /proc/cmdline 2>/dev/null
    if [[ $? == 0 ]]; then
        mkdir -p ${EDGE_WORK_DIR}/edge_portal
        cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/src ${EDGE_WORK_DIR}/edge_portal
        chown -R nobody:nobody ${EDGE_WORK_DIR}/edge_portal
    fi

    if [ -d  /usr/local/nginx/html/manager/i18n/ ]; then
        cp -f ${SRC_PATH}/software/edge_portal/alarm.xml/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/en-US/
        cp -f ${SRC_PATH}/software/edge_portal/alarm.xml/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/zh-CN/
        chown nobody:nobody /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml
        chmod 400 /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml
    fi

    if [ -d  /usr/local/nginx/html/manager/src/onlinehelp ]; then
        cp -rf ${SRC_PATH}/software/edge_portal/help/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/en/
        cp -rf ${SRC_PATH}/software/edge_portal/help/zh/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/
        chown -R nobody:nobody /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
        chmod 400 /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
    fi
}

function config_hw_user_group() {
    # check HwHiAiUser user and group exist
    egrep "^$HW_GROUP" /etc/group >&/dev/null || groupadd $HW_GROUP
    egrep "^$HW_USER" /etc/passwd >&/dev/null || useradd -g $HW_GROUP $HW_USER -s "$(type -p nologin)"
    [ ! -d ${HW_HOME} ] && mkdir -p ${HW_HOME} && chown $HW_USER:$HW_GROUP ${HW_HOME} && chmod 700 ${HW_HOME}
}

function config_src_path_and_file() {
    set_path_hw_usr_group ${SRC_PATH}
    set_path_hw_permission ${SRC_PATH} 700

    #set python code to be root owner as postern_main start as root user
    find ${SRC_PATH}/software/edge_site/ -name *.py -print0 | xargs -0 chown root:root -R
    find ${SRC_PATH}/software/edge_site/ -name *.py -print0 | xargs -0 chmod 700

}

function config_log_path_parent_dir()
{
    local parent_dir="$(dirname $LOG_PATH)"
    if [ -d "$parent_dir" ]; then
        set_path_hw_permission $parent_dir 755
    fi
}

function config_log_path_and_file() {
    config_log_path_parent_dir
    set_path_hw_usr_group ${LOG_PATH}
    set_path_hw_permission ${LOG_PATH} 700

    pushd ${LOG_PATH}
    local log_files=$(ls ${LOG_PATH})
    for log_file in ${log_files}; do
        chmod 600 ${log_file}
    done
    popd

    # set log rotate user and permission
    [ ! -d $LOG_ROTATE_PATH ] && mkdir -p $LOG_ROTATE_PATH
    chown $HW_USER:$HW_GROUP $(dirname $(dirname $LOG_ROTATE_PATH))
    chown $HW_USER:$HW_GROUP -R $(dirname $LOG_ROTATE_PATH)

}

function config_cfg_path_and_file() {
    set_path_hw_usr_group ${CFG_PATH}
    set_path_hw_permission ${CFG_PATH} 700

    set_file_hw_usr_permission ${SRC_PATH}/config/modelfiles.json 600
    set_file_hw_usr_permission ${SRC_PATH}/config/user_set_capablity.json 600
}

function config_sudoers_cmd_list() {
    local privilege_cmds_file="${SRC_PATH}/software/edge_site/edge_manager/src/script/privilege_cmd_list.txt"
    if [ ! -f ${privilege_cmds_file} ]; then
        return 1
    fi

    PYTHON_PATH=$(type -p python3)
    ATLASEDGE_SITE_BIN="${SRC_PATH}/software/edge_site/postern_main.py"
    ATLASEDGE_CORE_BIN="${SRC_PATH}/software/edge_core/edge_core"
    SUDO_ATLASEDGE_SITE_BIN="sudo -b ${PYTHON_PATH} ${ATLASEDGE_SITE_BIN}"
    sed -i "s|{WORK_PATH}|${SRC_PATH}|g" ${privilege_cmds_file}
    sed -i "s|{PYTHON_PATH}|${PYTHON_PATH}|g" ${privilege_cmds_file}
    sed -i "s|{ATLASEDGE_SITE_BIN}|${ATLASEDGE_SITE_BIN}|g" ${privilege_cmds_file}
    sed -i "s|{ATLASEDGE_CORE_BIN}|${ATLASEDGE_CORE_BIN}|g" ${privilege_cmds_file}
    sed -i "s|{SUDO_ATLASEDGE_SITE_BIN}|${SUDO_ATLASEDGE_SITE_BIN}|g" ${privilege_cmds_file}

    local temp_sudo_file_name="/tmp/sudoers_tmp"
    cp -af /etc/sudoers ${temp_sudo_file_name}
    if [[ $? != 0 ]]; then
        logger_Warn "cp sudoers failed"
        return 1
    fi
    cat ${privilege_cmds_file} | while read line || [[ -n ${line} ]];
    do
        if [[ -z "$line" ]] || [[ "$line" =~ ^#.* ]]; then
            continue
        fi
        update_cmd_into_sudoers ${temp_sudo_file_name} "$line"
        if [[ $? != 0 ]]; then
            logger_Warn "update cmd into sudoers failed"
            return 1
        fi
    done
    mv ${temp_sudo_file_name} /etc/sudoers
}

function update_cmd_into_sudoers() {
    local file_name="$1"
    shift
    local cmd="$*"
    cat /etc/sudoers | grep -F "$cmd" > /dev/null
    if [[ $? -eq 0 ]]; then
        return 0
    fi
    if [[ ! -f ${file_name} ]]; then
        logger_Warn "the tmp sudoers not exist"
        return 1
    fi
    echo "$cmd" >> ${file_name}
}

function config_other_file_privilege()
{
    chmod a+x $(type -p inotifywait)
    local mod_check_file="/run/atlasedge_mod_check.checksum"
    touch $mod_check_file
    chown HwHiAiUser:HwHiAiUser $mod_check_file
}

function main() {
    if [ ${#} -ne 3 ]; then
        echo "privilege config fail, parameter number error"
        return ${err_parameter_num_fail}
    fi
    SRC_PATH=$1
    LOG_PATH=$2
    CFG_PATH=$3
    WORK_DIR=$(dirname $(readlink -f "$SRC_PATH"))

    config_html_user_group
    config_hw_user_group
    config_src_path_and_file
    config_log_path_and_file
    config_cfg_path_and_file
    config_sudoers_cmd_list
    config_atlas_edge_privilege
    config_other_file_privilege
}

main "$@"
exit $?
